from info.modules.home import home_blu
from info import rs
from flask import current_app, render_template, session, jsonify, abort, request, g

from info.utils.common import user_login_data
from info.utils.constants import HOME_PAGE_MAX_NEWS
from info.utils.models import User, News, Category
from info.utils.response_code import RET, error_map


# 网站首页
@home_blu.route('/')
@user_login_data
def index():
    # 查询点击量排行前10的新闻
    try:
        rank_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except BaseException as e:
        current_app.logger.error(e)
        rank_list = []

    # 查询所有的分类数据
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    user = g.user.to_dict() if g.user else None

    # 将排行前10的新闻数据传入模板渲染
    return render_template("news/index.html", user=user, rank_list=rank_list, categories=categories)


# 设置网站小图标
@home_blu.route('/favicon.ico')
def favico():
    # 浏览器会自动向网站发起/favicon.ico请求来获取网站小图标  只请求一次
    # 网站只需要实现该路由, 并返回图标图片即可

    # flask中提供了一个读取静态文件内容的方法send_static_file
    # 该语法会将读取出的内容包装为响应对象并自动设置对应的content-type
    return current_app.send_static_file("news/favicon.ico")


# 获取新闻列表
@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get("cid")
    cur_page = request.args.get("cur_page")
    per_count = request.args.get("per_count", HOME_PAGE_MAX_NEWS)

    # 校验参数
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        cid = int(cid)
        cur_page = int(cur_page)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 数据库行为: 按照分类, 页码查询新闻  发布时间倒序
    filter_list = [News.status == 0]  # [News.status == 0]  过滤新闻的审核状态 审核通过的(status=0)才可以展示
    if cid != 1:  # 如果不是"最新"
        filter_list.append(News.category_id==cid)

    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 返回数据
    data = {
        "news_list": [news.to_dict() for news in pn.items],
        "total_page": pn.pages
    }
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)
